package com.lanxigua.entity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import com.lanxigua.utils.ErrorException;

import android.os.Message;
import android.util.Log;

public class Base<T> {
	public String string;
	public JSONObject json;
	public List<T> list = new ArrayList<T>();

	public Base() {

	}

	public Base(JSONObject json) {
		this.string = json.toString();
		this.json = json;

		Field[] fields = this.getClass().getFields();
		if (json != null && json.length() != fields.length) {
			// Log.e(this.getClass().getName(),
			// "There isn't equal between json object and class property. Please check again.");
		}

		for (int i = 0; i < fields.length; i++) {
			try {
				Field field = this.getClass().getDeclaredField(
						fields[i].getName());
				if (json.has(fields[i].getName())) {
					// if (fields[i].getType().toString() == "java.lang.String")
					// {
					// Log.i("TYPE", fields[i].getType().toString());
					field.set(this, json.getString(fields[i].getName()));
					// }else{
					// Constructor c =
					// this.getClass().getConstructor(JSONObject.class);
					// field.set(this,
					// c.newInstance(json.getJSONObject((fields[i].getName()))));
					// }
				} else {
					Log.e("TYPE", "There isn't " + fields[i].getName()
							+ " property in json object. Please check again.");
				}
			} catch (Exception e) {
				// Log.e(this.getClass().getName(), e.getLocalizedMessage());
			}
		}
	}

	public Base(Message message) throws ErrorException {
		if (message.what == 0) {
			Field[] fields = this.getClass().getFields();
			try {
				if (message.obj.getClass() == Class
						.forName("org.json.JSONObject")) {
					json = ((JSONObject) message.obj);
					
					for (int i = 0; i < fields.length; i++) {
						try {
							Field field = this.getClass().getDeclaredField(
									fields[i].getName());
							if (json.has(fields[i].getName())) {								
								field.set(this, json.getString(fields[i].getName()));
							} 
						} catch (Exception e) {
							
						}
					}
				} else if (message.obj.getClass() == Class
						.forName("org.json.JSONArray")) {
					return;
				}
			} catch (ClassNotFoundException e1) {
				
			}
		}else if (message.what == -1){
			throw new ErrorException(message.obj.toString());
		}		
	}
}